package collection.set;

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        // 1. 存储基本类型（自动排序）
        Set<Integer> numbers = new TreeSet<>();
        numbers.add(30);
        numbers.add(10);
        numbers.add(20);
        numbers.add(10); // 重复元素，添加失败
        System.out.println("排序后的数字：" + numbers); // [10, 20, 30]

        // 2. 存储字符串（按自然顺序排序）
        Set<String> words = new TreeSet<>();
        words.add("banana");
        words.add("apple");
        words.add("cherry");
        System.out.println("排序后的字符串：" + words); // [apple, banana, cherry]

        // 3. 自定义排序（使用Comparator）
        Set<Student> students = new TreeSet<>((s1, s2) -> {
            // 按年龄升序，年龄相同按姓名降序
            if (s1.getAge() != s2.getAge()) {
                return Integer.compare(s1.getAge(), s2.getAge());
            }
            return s2.getName().compareTo(s1.getName());
        });

        students.add(new Student("张三", 20));
        students.add(new Student("李四", 18));
        students.add(new Student("王五", 20));

        System.out.println("\n自定义排序的学生：");
        for (Student s : students) {
            System.out.println(s);
        }
    }

    static class Student {
        private String name;
        private int age;

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() { return name; }
        public int getAge() { return age; }

        @Override
        public String toString() {
            return name + "(" + age + ")";
        }
    }
}
